from django import forms
from .models import KeHu, KeHuzilao, KeHugenjinlog,KeHu_zhaungtai
from django.forms import inlineformset_factory
from django.contrib.auth.models import User
from django.db.models import Value
from django import forms
from TuiGuang.models import tg_qudao



class CustomModelChoiceField(forms.ModelChoiceField):
    def __init__(self, *args, label_from_instance=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.label_from_instance = label_from_instance

    def label_from_instance(self, obj):
        if self.label_from_instance is not None:
            return self.label_from_instance(obj)
        return super().label_from_instance(obj)

class KeHuForm(forms.ModelForm):
    """客户新增表单"""
    tg_qudao = CustomModelChoiceField(
        queryset=tg_qudao.objects.all(),
        label='数据来源',
        empty_label='请选择',
        required=False,
        widget=forms.Select(attrs={'class': 'form-control'}),
        label_from_instance=lambda obj: f"{obj.name}-({obj.tg_leixing})"  # 自定义显示格式
    )

    beizhu = forms.CharField(
        widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '3', 'cols': '100px', 'placeholder': '请在此处填写备注信息...,如：客户类型、行业等 '}),
        required=False , # 设置beizhu字段为非必需
        label='备注',

    )

    class Meta:
        model = KeHu
        fields = ['username', 'name', 'tel', 'beizhu', 'zixuntime','tg_qudao']
        widgets = {
            'username': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入用户名'}),
            'name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入姓名'}),
            'tel': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入手机号码'}),
            'beizhu': forms.Textarea(attrs={'class': 'form-control', 'rows': '3', 'cols': '100px'}),
           # 'zixuntime': forms.DateField(input_formats=['%Y-%m-%d'],widget=forms.DateInput(attrs={'type': 'date', 'class': 'form-control'})),
            'zixuntime': forms.DateTimeInput(attrs={'type': 'datetime-local','class': 'form-control'}),
         #   'admin_user': forms.Select(attrs={'class': 'form-control'}) #删除admin_user字段 改为是视图处理
        }
    def clean_tel(self):
        tel = self.cleaned_data.get('tel')
        # 如果是更新操作，并且当前实例的电话号码没有改变，则不触发验证
        if self.is_update and self.instance.pk and self.instance.tel == tel:
            return tel
        # 如果是新增操作或者电话号码已更改，则检查重复
        if KeHu.objects.filter(tel=tel).exclude(pk=self.instance.pk).exists():
            raise forms.ValidationError('该手机号码已存在，请重新输入。')
        return tel

    def save(self, commit=True):
        # 首先保存 KeHu 实例
        kehu_instance = super().save(commit=False)
        if commit:
            kehu_instance.save()
        # 如果还没有关联的 KeHu_zhaungtai 实例，则创建一个新的
        kehu_zhaungtai, created = KeHu_zhaungtai.objects.get_or_create(kehu=kehu_instance)
        # 如果是新创建的，则保存
        if created:
            kehu_zhaungtai.save()
        # 关联 KeHu 实例与 KeHu_zhaungtai 实例
        kehu_instance.kehu_zhaungtai = kehu_zhaungtai
        if commit:
            kehu_instance.save()
        return kehu_instance

    def __init__(self, *args, **kwargs):
        self.is_update = kwargs.pop('is_update', False)  # 添加is_update参数，默认为False
        super(KeHuForm, self).__init__(*args, **kwargs)
        self.fields['tg_qudao'].required = True


class KeHuzilaoForm(forms.ModelForm):
    """客户资料表单"""
    hujileixing = forms.CharField(
        required=False,  # 设置beizhu字段为非必需
    )
    hujizhenghao = forms.CharField(
        required=False,  # 设置beizhu字段为非必需
    )
    fujian = forms.CharField(
        required=False,  # 设置beizhu字段为非必需
    )
    class Meta:
        model = KeHuzilao
        fields = ['hujileixing', 'hujizhenghao', 'fujian']  # 根据需要调整字段


        def save(self, commit=True):
            instance = super().save(commit=False)
            if 'fujian' in self.files:
                instance.fujian = self.files['fujian']
            if commit:
                instance.save()
            return instance

# KeHuFormSet = inlineformset_factory(KeHu, KeHuzilao, fields=['hujileixing', 'hujizhenghao', 'fujian']) 在用户新增页面直接添加用户资料，不需要再单独添加用户资料
class KeHugenjinlogForm(forms.ModelForm):
    """客户资料表单"""
    class Meta:
        model = KeHugenjinlog
        widgets = {
            'genjinleixing': forms.Select(attrs={'class': 'form-control form-control-sm'}),
            'genjintext': forms.Textarea(attrs={'class': 'form-control', 'rows': '3', 'cols': '100px'}),
            'genjintime': forms.DateTimeInput(attrs={'class': 'form-control', 'type': 'datetime-local'}),
        }
        fields = ['genjinleixing', 'genjintext','genjintime']
        labels = {
            'genjinleixing': '跟进类型',
            'genjintext': '跟进内容',
        }

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.fields['genjinleixing'].empty_label = "请选择"

class KeHu_zhaungtaiForm(forms.ModelForm):
    yixiangdu = forms.CharField(
        required=False,  # 设置beizhu字段为非必需
    )
    youxiaoif = forms.CharField(
        required=False,  # 设置beizhu字段为非必需
    )
    guanzhu = forms.CharField(
        required=False,  # 设置beizhu字段为非必需
    )
    class Meta:
        model = KeHu_zhaungtai
        fields = ['yixiangdu', 'youxiaoif', 'guanzhu','kehu']



class KeHu_zhuangonghai_Form(forms.ModelForm):
    class Meta:
        model = KeHu
        fields = ['if_gonghai']  # 移除 'admin_user'
        widgets = {
            'if_gonghai': forms.RadioSelect(attrs={'class': 'form-check-input'}),
        }

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super().__init__(*args, **kwargs)
        if self.request and self.request.user.is_authenticated:
            self.initial['admin_user'] = self.request.user.id  # 设置初始值，但不会在前端显示

